package core;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.TreeMap;
import java.util.Map.Entry;
import java.util.NoSuchElementException;

import util.Constants;

import network.TENetwork;


import data.ScheduleParser;
import database.Saver;
import entities.ScheduleDate;
import entities.ScheduleDay;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class Main extends Activity {

	static AppSettings appSettings = new AppSettings(); // settings
	private Saver saver; // saver/ loader class
	private TENetwork teNetwork;
	private ScheduleParser scheduleParser;
	private AppState appState;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		teNetwork = new TENetwork(); // start network connection to
										// TimeEdit
										// server
		scheduleParser = new ScheduleParser();
		appState = new AppState();
		// AppSettings appSettings = new AppSettings();

		/*
		 * TextView tv = new TextView(this); tv.setText("Hello, Android");
		 * setContentView(tv);
		 */

		initMenus();
	}

	private void initMenus() {
		/* Runs the main menu upon startup. */
		startActivityForResult(new Intent("te.MENUACTIVATION"),
				Constants.TRIGGERMENU);

	}

	/*
	 * This is basically the "event listener". It receives a code from an
	 * (terminated) activity and decides what to do with it.
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		/*
		 * Responses from the Main Menu about activating another menu.
		 */
		if (requestCode == Constants.TRIGGERMENU) {
			if (resultCode == Constants.RESPONSEMAINTOSEARCH) {
				Intent intent = new Intent("te.SEARCHACTIVATION");
				intent.putExtra("searchCode", appState.getCurrentList());
				startActivityForResult(intent, Constants.TRIGGERSEARCH);
			} else if (resultCode == Constants.RESPONSEMAINTOSETTINGS) {
				startActivityForResult(new Intent("te.SETTINGSACTIVATION"),
						Constants.TRIGGERSETTINGS);
			} else if (resultCode == Constants.RESPONSEMAINTOSAVEDONE) {
				startActivityForResult(new Intent("te.SCHEDULEDAYACTIVATION"),
						Constants.TRIGGERSCHEDULEDAY);
			} else {
				startActivityForResult(new Intent("te.MENUACTIVATION"),
						Constants.TRIGGERMENU);
			}
		}
		
		
		/*
		 * Responses from the Search menu.
		 */
		if (requestCode == Constants.TRIGGERSEARCH) {
			
			/*
			 * Response to view a list of hits
			 */
			if (resultCode == Constants.RESPONSEMAINTOSEARCH) {

				
				String[] searchQuery = data.getStringArrayExtra("Search");
				Object obj = data.getSerializableExtra("searchCode");
				if(obj != null){
					appState.setCurrentList((HashMap<String,Integer>)obj);
				}
				HashMap<String, Integer> hm = null;
				try {

					String checkURL = TENetwork.createSearchURL(searchQuery);

					LinkedList<String> checkString = teNetwork
							.getRawDataFromServer(checkURL);

					hm = scheduleParser.makeSearchPretty(checkString);

				} catch (IOException e) {
					Toast.makeText(
							Main.this,
							"Could not connect to server. Verify that the phone is online."
									+ searchQuery[0] + ", " + searchQuery[1],
							Toast.LENGTH_SHORT).show();
					startActivityForResult(new Intent("te.SEARCHACTIVATION"),
							Constants.TRIGGERSEARCH);
				} catch (NoSuchElementException e) {
					hm = new HashMap<String, Integer>();
				}

				if ((!(hm.isEmpty())) && (hm != null)) {
					for (Entry<String, Integer> k : hm.entrySet()) {
						System.out.println("Course: " + k.getKey() + " Code: "
								+ k.getValue());
					}
					Intent intent = new Intent("te.SEARCHHITSACTIVATION");
					intent.putExtra("queryMap", hm);
					startActivityForResult(intent, Constants.TRIGGERSEARCHHITS);
				} else {
					Toast.makeText(
							Main.this,
							"No results were found." + searchQuery[0] + ", "
									+ searchQuery[1], Toast.LENGTH_SHORT)
							.show();
					startActivityForResult(new Intent("te.SEARCHACTIVATION"),
							Constants.TRIGGERSEARCH);
				}
	
				

			
			}
			
			/*
			 * User has pressed back from the search menu.
			 */
			if (resultCode == Constants.RESPONSESEARCHSTARTMAIN) {
				startActivityForResult(new Intent("te.MENUACTIVATION"),
						Constants.TRIGGERMENU);
			}
			if (resultCode == Constants.RESPONSESEARCHSTARTMAINALTERED) {
				appState.setCurrentList((HashMap<String, Integer>)data.getSerializableExtra("searchCode") );
				startActivityForResult(new Intent("te.MENUACTIVATION"),
						Constants.TRIGGERMENU);
			}
			// startActivityForResult(new Intent("te.MENUACTIVATION"),
			// Constants.TRIGGERMENU);
		}
		
		/*
		 * Responses from the SearchHits menu.
		 */
		if (requestCode == Constants.TRIGGERSEARCHHITS) {
			if(resultCode == Constants.RESPONSESHSTARTVIEW){
				String src = TENetwork.createScheduleURL(data.getIntExtra("searchCode", 0));
				System.out.println(src);
				TreeMap<ScheduleDate, ScheduleDay> scheduleMap;
				try {
					scheduleMap = scheduleParser.makeDateMapSingle(scheduleParser.makeSchedulePretty(teNetwork.getRawDataFromServer(src)));
				} catch (IOException e) {
					scheduleMap = new TreeMap<ScheduleDate, ScheduleDay>();
					e.printStackTrace();
				}
				Intent intent = new Intent("te.SCHEDULEDAYACTIVATION");
				intent.putExtra("scheduleMap", scheduleMap);
				startActivityForResult(intent,
						Constants.TRIGGERSCHEDULEDAY);
				
			}
			if(resultCode == Constants.RESPONSESHSTARTVIEWALTERED){
				TENetwork.createScheduleURL(data.getIntExtra("searchCode", 0));
				
				appState.setCurrentList((HashMap<String, Integer>)data.getSerializableExtra("selectedMap") );
				//TODO start ScheduleDayDrawer!
			}
			if(resultCode == Constants.RESPONSESHSTARTSEARCH){
				Intent intent = new Intent("te.SEARCHACTIVATION");
				intent.putExtra("searchCode", appState.getCurrentList());
				startActivityForResult(intent,
						Constants.TRIGGERSEARCH);
			}
			if(resultCode == Constants.RESPONSESHSTARTSEARCHALTERED){
				HashMap<String, Integer> newMap = appState.getCurrentList();
				newMap.putAll( (HashMap<String, Integer>)data.getSerializableExtra("selectedMap"));
				appState.setCurrentList(newMap);
				Intent intent = new Intent("te.SEARCHACTIVATION");
				intent.putExtra("searchCode", appState.getCurrentList());
				startActivityForResult(intent,
						Constants.TRIGGERSEARCH);
			}
		}
		
		/*
		 * Response from the settings menu. Probably pressed "back".
		 */
		if (requestCode == Constants.TRIGGERSETTINGS) {
			startActivityForResult(new Intent("te.MENUACTIVATION"),
					Constants.TRIGGERMENU);
		}
		if (requestCode == Constants.TRIGGERSCHEDULEDAY) {
			if (resultCode == 13) {
				startActivityForResult(new Intent("te.SCHEDULEDAYACTIVATION"),
						Constants.TRIGGERSCHEDULEDAY);
			}
			else
			startActivityForResult(new Intent("te.MENUACTIVATION"),
					Constants.TRIGGERMENU);
		}

	}
	
	

	private void getSaves() {

	}

	public static AppSettings getAppSettings() {
		return appSettings;
	}

	public static void setAppSettings(AppSettings appSettings) {
		Main.appSettings = appSettings;
	}

	private void loadSettings() {

	}

}
